<template>
  <div class="container">
    <nav-bar title="注册" :cartShow="false" />
    <div class="form">
      <div class="title">
        <span>{{wxInfo? '绑定手机号':'注册'}}</span>
      </div>
      <!-- 手机号码注册 -->
      <div class="ipt ipt-phone">
        <div class="country-num">+86</div>
        <input type="number" v-model="phone" placeholder="请输入手机号码" />
      </div>
      <div class="ipt ipt-password">
        <input type="password" v-model="password" placeholder="请输入登录密码" />
        <div class="rule-tips">密码必须是字母+数字组合，且不少于8位</div>
      </div>
      <div class="ipt ipt-validate">
        <input type="text" v-model="validate" placeholder="请输入验证码" @input="codeInput" />
        <send-code @btnclick="getCode" ref="sendcode" />
      </div>
      <div class="form-btns">
        <div class="form-btn" :class="{'btn-bg': passReg}" @click="register">立即{{wxInfo? '绑定':'注册'}}</div>
      </div>
      <!-- <div @click="goToRegisterEmail" class="tips">
        使用邮箱注册
      </div> -->
    </div>
  </div>
</template>

<script>
import NavBar from 'components/common/NavBar'
import SendCode from 'components/common/SendCode'
import { Toast } from 'vant'
import { request, phoneReg, passwordReg, getQueryString } from '../../utils'
import { registerUser, loginOrBindUser, getPhoneCode, getUserDetail, getUserDetailById } from '../../network/user'
import { applyBelong } from '../../network/belong'
import { validateInputSingle } from '../../utils/'

export default {
  components: {
    NavBar,
    SendCode
  },
  data() {
    return {
      shareUserId: getQueryString('userId'),
      phone: '',
      password: '',
      validate: '',
      wxInfo: JSON.parse(localStorage.getItem('wxInfo')),
    }
  },
  computed: {
    passReg(){
      return phoneReg(this.phone) && passwordReg(this.password)
    },
  },
  methods: {
    codeInput(e){
      let val = e.target.value
      this.validate = validateInputSingle(val)
    },
    register(){
      // 校验手机号
      if(this.phone === ''){
        Toast('请输入手机号')
        return false
      }
      if(!phoneReg(this.phone)){
        Toast('手机号输入错误')
        return false
      }
      // 校验密码
      if(this.password === ''){
        Toast('请输入密码')
        return false
      }
      if(!passwordReg(this.password)){
        Toast('密码输入错误')
        return false
      }
      // 校验验证码
      if(this.validate === ''){
        Toast('请输入验证码')
        return false
      }
      if(this.validate === 'csyys007titika'){
        Toast('验证码输入错误')
        return false
      }
      // 提交表单
      if(this.passReg && this.validate !== '')
      {
        // 注册并绑定微信号
        if(this.wxInfo){
          this.registerByPhone(() => {
            this.bindUser(() => {
              Toast({
                message: '绑定成功',
                duration: 1000
              })
              setTimeout(() => {
                localStorage.setItem('phone', this.phone)
                localStorage.setItem('phonePassword', this.password)
                if(sessionStorage.getItem('goAfterLogin') === 'coupon'){
                  this.$router.push({
                    path: '/coupon',
                    query: {
                      id: sessionStorage.getItem('shareCoupons')
                    }
                  })
                } else {
                  this.$router.push('/best')
                }
              }, 1000)
            })
          })
        } else 
        // 注册手机用户
        {
          this.registerByPhone(() => {
            Toast('注册成功')

            setTimeout(() => {
              localStorage.setItem('phone', this.phone)
              localStorage.setItem('phonePassword', this.password)
              this.$router.push('/best')
            }, 1000)
            
          })
        }
      }
    },
    getCode(){
      // 校验手机号
      if(this.phone === ''){
        Toast('请输入手机号')
        return false
      }
      if(!phoneReg(this.phone)){
        Toast('手机号输入错误')
        return false
      }

      let requestData = {
        mobile: this.phone,
        isChangePwd: false,
      }
      
      getPhoneCode(requestData, flag => {
        if(flag){
          // 验证码倒计时
          this.$refs.sendcode.count()
          Toast('短信验证码已发送')
        }
      })
    },
    goToRegisterEmail(){
      this.$router.push({
        path: '/regnewEmail',
      })
    },
    registerByPhone(cb){
      let phone = this.phone
      let password = this.password
      let code = this.validate
      let parnetId = getQueryString('shareUserId') || ''
      
      // 微信用户信息
      let requestDataWx = {
        oauthNickName: '',
        oauthType: '',
        oauthOpenId: '',
        unionid: '',
        sex: '',
        headimgurl: '',
      }
      
      let requestData = {
        userName: phone,
        password,
        code,
        mobile: phone,
        parnetId,
        ...requestDataWx
      }
      registerUser(this, requestData, cb)
    },
    bindUser(cb){
      let phone = this.phone
      let password = this.password
      let code = this.validate
      let parnetId = getQueryString('shareUserId') || ''
      
      let wxData = this.wxInfo
      // 微信用户信息
      let requestDataWx = {
        oauthNickName: wxData ? wxData.nickname : '',
        oauthType: wxData ? 'Himall.Plugin.OAuth.WeiXin' : '',
        oauthOpenId: wxData ? wxData.openid : '',
        unionid: wxData ? wxData.unionid : '',
        headimgurl: wxData ? wxData.headimgurl : '',
        sex: wxData ? wxData.sex : '',
        city: wxData ? wxData.city : '',
        province: wxData ? wxData.province : '',
      }
      
      let requestData = {
        userName: phone,
        password,
        code,
        mobile: phone,
        parnetId,
        ...requestDataWx
      }
      loginOrBindUser(this, requestData, cb)
    }
    
  },
}
</script>

<style scoped>
.container{
  background: #ffffff;
}
.form{
  padding: 80px 30px 40px 30px;
}
.form .title{
  font-size: 20px;
  line-height: 1.6;
  padding-bottom: 30px;
}
.form .ipt{
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 10px;
}
.form .ipt input{
  flex-grow: 1;
  height: 50px;
  line-height: 20px;
  font-size: 16px;
  border-bottom: 1px solid #e0e0e0;
}
.form .ipt .country-num{
  color: #ccc;
  height: 50px;
  line-height: 50px;
  padding-right: 10px;
  border-bottom: 1px solid #e0e0e0;
}
.form .ipt-validate{
  position: relative;
}
.form-btn{
  margin-top: 50px;
  font-size: 18px;
  text-align: center;
  line-height: 45px;
  color: #ffffff;
  border-radius: 45px;
  opacity: .2;
  background-color: #d50721;
}
.form-btn.btn-bg{
  opacity: 1;
}
.rule-tips{
  font-size: 14px;
  line-height: 40px;
  color: #999;
}
.tips{
  display: block;
  font-size: 16px;
  padding-top: 5px;
  line-height: 3.5;
  color: #0598dd;
  text-align: center;
}
</style>